package exogwt.server.jcr.url;

import org.exoplatform.services.jcr.RepositoryService;
import org.exoplatform.services.jcr.impl.core.CredentialsImpl;
import org.exoplatform.services.jcr.config.RepositoryConfigurationException;

import javax.jcr.Session;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Node;
import java.net.URLConnection;
import java.net.URL;
import java.io.IOException;
import java.io.InputStream;

public class JcrUrlConnection extends URLConnection {
    private RepositoryService repositoryService;
    private Session session;

    public JcrUrlConnection(URL url, RepositoryService repositoryService) {
        super(url);
        this.repositoryService = repositoryService;
    }

    public void connect() throws IOException {
        try {
            Repository repository = repositoryService.getRepository();
            String userInfo = url.getUserInfo();
            String host = url.getHost();
            if (userInfo != null) {
                CredentialsImpl credentials = getCredentials(userInfo);
                session = repository.login(credentials, host);
            } else {
                session = repository.login(host);
            }
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

    private CredentialsImpl getCredentials(String userInfo) {
        int separatorIndex = userInfo.indexOf(":");
        String login;
        String password;
        if (separatorIndex > 0) {
            login = userInfo.substring(0, separatorIndex);
            password = userInfo.substring(separatorIndex + 1);
        } else {
            login = userInfo;
            password = "";
        }
        return new CredentialsImpl(login, password.toCharArray());
    }

    public InputStream getInputStream() throws IOException {
        connect();
        try {
            String path = url.getPath();
            if (path.length() > 0) {
                path = path.substring(1); // replace leading slash
            }

            Node node = session.getRootNode();
            if (path.length() > 0) {
                node = node.getNode(path);
            }
            node = node.getNode("jcr:content");
            return node.getProperty("jcr:data").getStream();
        } catch (RepositoryException e) {
            throw new IOException(e.getMessage());
        }
    }
}
